<template>
  <view class="category-tabs">
    <scroll-view 
      class="tabs-scroll" 
      scroll-x 
      :scroll-left="scrollLeft"
      :scroll-with-animation="true"
      enable-flex
    >
      <view class="tabs-container">
        <view 
          v-for="(item, index) in categories" 
          :key="item.id"
          class="tab-item"
          :class="{ active: currentCategory === item.id }"
          :id="`tab-${index}`"
          @click="selectCategory(item.id, index)"
        >
          <text class="tab-text">{{ item.name }}</text>
          <view v-if="item.count > 0" class="tab-count">{{ item.count }}</view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch, getCurrentInstance, nextTick } from 'vue'
import { useImageStore } from '@/stores/image'
import { getCategoryList } from '@/api/image'

const instance = getCurrentInstance()
const imageStore = useImageStore()
const categories = ref([])
const currentCategory = ref('all')
const scrollLeft = ref(0)

onMounted(() => {
  loadCategories()
  currentCategory.value = imageStore.currentCategory
})

// 监听 store 中的分类变化
watch(() => imageStore.currentCategory, (newCategory) => {
  currentCategory.value = newCategory
  nextTick(() => {
    scrollToActiveTab()
  })
})

function loadCategories() {
  getCategoryList().then(res => {
    if (res.code === 200 && res.data) {
      categories.value = res.data
      imageStore.setCategories(res.data)
      // 初始化时滚动到当前选中的分类
      nextTick(() => {
        scrollToActiveTab()
      })
    }
  }).catch(err => {
    console.error('加载分类列表失败:', err)
    // 使用默认分类
    const defaultCategories = [
      { id: "all", name: "全部", slug: "all", count: 0 }
    ]
    categories.value = defaultCategories
    imageStore.setCategories(defaultCategories)
  })
}

function selectCategory(categoryId, index) {
  if (currentCategory.value === categoryId) {
    return // 已经是当前分类
  }
  
  currentCategory.value = categoryId
  imageStore.setCategory(categoryId)
  
  // 滚动到选中的分类
  nextTick(() => {
    scrollToTab(index)
  })
}

function scrollToTab(index) {
  // 使用 uni.createSelectorQuery 获取元素位置并滚动
  const query = uni.createSelectorQuery().in(instance)
  query.select(`#tab-${index}`).boundingClientRect((data) => {
    if (data) {
      // 获取系统信息，计算 rpx 转换比例
      const systemInfo = uni.getSystemInfoSync()
      const pixelRatio = 750 / systemInfo.windowWidth // rpx 转换比例
      
      // 计算需要滚动的距离（rpx）
      const scrollViewWidth = 750 // 视口宽度（rpx）
      const itemLeft = data.left * pixelRatio // 转换为 rpx
      const itemWidth = data.width * pixelRatio // 转换为 rpx
      const itemCenter = itemLeft + itemWidth / 2
      
      // 计算滚动位置，让选中的分类居中
      const targetScrollLeft = itemCenter - scrollViewWidth / 2
      
      scrollLeft.value = Math.max(0, targetScrollLeft)
    }
  }).exec()
}

function scrollToActiveTab() {
  const activeIndex = categories.value.findIndex(item => item.id === currentCategory.value)
  if (activeIndex >= 0) {
    scrollToTab(activeIndex)
  }
}
</script>

<style scoped>
.category-tabs {
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 88rpx; /* 导航栏高度 */
  z-index: 99;
}

.tabs-scroll {
  white-space: nowrap;
  width: 100%;
  height: 88rpx;
  /* 隐藏滚动条但保持滚动功能 */
  /* #ifdef H5 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  /* #endif */
}

/* #ifdef H5 */
.tabs-scroll::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
/* #endif */

.tabs-container {
  display: inline-flex;
  align-items: center;
  padding: 0 20rpx;
  height: 100%;
  min-width: 100%;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  height: 60rpx;
  min-width: fit-content;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background-color: #f5f5f5;
  transition: all 0.3s;
  white-space: nowrap;
  position: relative;
  flex-shrink: 0;
}

.tab-item.active {
  background-color: #007AFF;
  color: #fff;
}

.tab-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
  line-height: 1;
}

.tab-item.active .tab-text {
  color: #fff;
  font-weight: 600;
}

.tab-count {
  margin-left: 8rpx;
  font-size: 22rpx;
  color: #999;
  background-color: rgba(0, 0, 0, 0.1);
  padding: 2rpx 8rpx;
  border-radius: 10rpx;
}

.tab-item.active .tab-count {
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(255, 255, 255, 0.2);
}
</style>

